/*
版权所有 (c)  小亮同学
依据木兰宽松许可证第2版（Mulan PSL v2）获得许可。
您可以在 http://license.coscl.org.cn/MulanPSL2 获取许可证的完整文本。
*/
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using AliDDNS.Configuration;
using AliDDNS.Model;

namespace AliDDNS.Service;

public sealed class WindowsBackgroundService(ILogger<WindowsBackgroundService> logger, AllDNSRecord allDNS, IConfiguration configuration) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        try
        {
            allDNS.GetAllDNSRecord( );
            while (!stoppingToken.IsCancellationRequested)
            {
                DDNSConfig config = configuration.GetSection("DDNS")?.Get<DDNSConfig>( ) ?? throw new Exception("配置文件错误");

                NetworkInterface[] networks = [.. NetworkInterface.GetAllNetworkInterfaces( ).Where(o => o.OperationalStatus == OperationalStatus.Up)];
                var IPs = networks.SelectMany(o => o.GetIPProperties( ).UnicastAddresses).ToList( );
                IPAddress? ip = IPs.FirstOrDefault(o => o.SuffixOrigin == SuffixOrigin.LinkLayerAddress
                                                  && !o.Address.IsIPv6LinkLocal
                                                  && o.Address.AddressFamily == AddressFamily.InterNetworkV6
                                                  && o.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred)?.Address;
                if (ip is null)
                {
                    logger.LogWarning("未找到匹配IP");
                    await Task.Delay(TimeSpan.FromMinutes(config.Interval / 10), stoppingToken);
                    continue;
                }
                logger.LogInformation("获取到IP：{ip}", ip);
                try
                {
                    DNSRecord record = allDNS.DNSRecords.First(o => o.Type == config.Type && o.RR == config.RR && o.DomainName == config.DomainName);
                    logger.LogInformation("找到匹配记录：{record.RecordId}", record.RecordId);
                    record.Value = ip?.ToString( ) ?? "";
                }
                catch (ArgumentNullException)
                {
                    logger.LogWarning("未找到匹配记录");
                    DNSRecord record = new(configuration, logger, ip?.ToString( ));
                    allDNS.DNSRecords.Add(record);
                    logger.LogInformation("新增解析记录{record.RecordId}", record.RecordId);
                }
                await Task.Delay(TimeSpan.FromMinutes(config.Interval), stoppingToken);
            }
        }
        catch (HttpRequestException ex)
        {
            logger.LogError(ex, "网络请求出错，请检查网络");
        }
        catch (OperationCanceledException)
        {
            logger.LogInformation("程序已退出");
            Environment.Exit(0);
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "未知错误：请检查配置文件是否正确配置");
        }
    }
}
